<template>
  <div v-if="!loadingStore.loading">
     <!-- 导航栏 -->
  <MakeNavBar @reset="resetHandler" @loadPDF="downLoadPDF"></MakeNavBar>
  <!-- 内容区域 -->
  <div class="big_box">
    <!-- 左测区域 -->
    <LeftModel></LeftModel>
    <!-- 中间简历内容区域 -->
    <div class="container_center">
      <!-- 滚动条el-scrollbar会占据一定的高度 -->
      <!-- <el-scrollbar height="85vh"> -->
      <CScrollbar>
        <div id="capture">
          <CenterModel v-if="flag" ref="center"></CenterModel>
        </div>
      </CScrollbar>
      <!-- </el-scrollbar> -->
    </div>
    <!-- 右侧区域 -->
    <div class="container_right">
      <RightModel></RightModel>
    </div>
  </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import MakeNavBar from '@/view/Make/components/makeNavBar/makeNavBar.vue'
import CenterModel from '@/view/Make/components/centerModel/centerModel.vue'
import LeftModel from '@/view/Make/components/leftModel/leftModel.vue'
import RightModel from '@/view/Make/components/rightModel/rightModel.vue'
import Loading from '@/components/Loading/Loading.vue'
import useLoadingStore from '@/store/loading.ts'
import { CScrollbar } from 'c-scrollbar' //滚动条
import { useRoute } from 'vue-router'
import { getTemplateJson } from '@/api/getTemplate'
import { cloneDeep } from 'lodash'
import MODEL_DATA_JSON from '@/schema/modelData'
import { onMounted, watch, getCurrentInstance } from 'vue'
import { storeToRefs } from 'pinia'
import { useResumeJsonStore, useSelectMaterialStore } from '@/store/resume'
import { ElMessage, ElMessageBox } from 'element-plus'
import htmlToPdf from '@/util/downLoadPDF2.ts'
let loadingStore = useLoadingStore()
let userResumeStore = useResumeJsonStore()
let useSelectMaterial = useSelectMaterialStore()
let route = useRoute()
const flag = ref(false)
const { id, name } = route.query
const center = ref(null)

//在组件挂载完毕监听高度
onMounted(() => {
  resumeChangeHeight()
})
//获取本地数据--location.origin本地地址
const resetStoreLocal = async () => {
  loadingStore.closeOrOpenLoadingStatus(true)

  // 获取id对应的模板数据
  const url = `${location.origin}/json/${name}/template.json`
  const { data: res } = await getTemplateJson(url)
  let template_json = {
    ...cloneDeep(res),
    ID: id,
    NAME: name
  }
  template_json.COMPONENTS.forEach((item) => {
    item.data = MODEL_DATA_JSON[item.model]
  })
  userResumeStore.changeResumeJsonData(template_json)

  // 第一次请求后，存储模板数据，避免二次请求
  const beforeTemplateData = JSON.parse(localStorage.getItem('templateData') || '{}')
  const newDataStorage = { ...beforeTemplateData, [id]: template_json }
  localStorage.setItem('templateData', JSON.stringify(newDataStorage))
  flag.value = true
  loadingStore.closeOrOpenLoadingStatus(false)
}

const getCacheData = () => {
  // 缓存的草稿数据
  const draftData = localStorage.getItem('resumeDraft')
  if (draftData) {
    return JSON.parse(draftData)[id]
  }
  // 缓存的模板数据
  const templateData = localStorage.getItem('templateData')
  if (templateData) {
    return JSON.parse(templateData)[id]
  }
  return {}
}

//  resetStoreLocal()
//进入简历页面，初始化
// 获取已缓存的模板数据，避免二次请求
const cacheData = getCacheData()
const notNullObject=JSON.stringify(cacheData)!=='{}'
console.log(notNullObject)
if (cacheData&&notNullObject) {
  //使用用户更新过的简历模板数据
  userResumeStore.changeResumeJsonData(cacheData)
  flag.value = true
  loadingStore.closeOrOpenLoadingStatus(false)
  // console.log('本地有缓存这个id模板')
  // console.log('cacheData有值',11111)
  console.log(cacheData)
} else {
  // console.log('本地无缓存,使用默认模板数据')
  // console.log('cacheData无值,发起请求数据',11111)
  resetStoreLocal()
}

//监听简历页面高度
const linesNumber = ref(0)
//获得循环生成动态的分隔线的dom节点（是一个数组）
const resumeChangeHeight = function () {
  const myObserve = new ResizeObserver((entires) => {
    //emtires是一个数组包含 entry.target指触发对象的DOM节点本身 和  entry.contentBox
    for (let entry of entires) {
      //简历的高度 1160px是简历样式设置的min-height
      let height = (entry.target as HTMLElement).offsetHeight
      linesNumber.value = Math.ceil(height / 1160)
      // leftBox.style.height=`${1160*linesNumber}px`
      //放在外面linesItem为null
      //       nextTick(() => {
      //         console.log(linesItem.value[linesNumber.value - 1])
      //          //最后一条分割线
      //         // linesItem.value[linesNumber.value - 1].style.top=`${linesNumber}px`
      //       })
    }
  })
  //开启监听
  try {
    myObserve.observe(center.value.$el)
  } catch (error) {
    console.log(error)
  }
}

// 导出为PDF
// const downLoadPDF=async()=>{
// let temp = linesNumber.value
// linesNumber.value = 0
// useSelectMaterial.resetSelectMaterial() // 重置选中模块
// await nextTick()
// downLoadPDF(center.value.$el, userResumeStore.resumeJsonNewStore.TITLE,  () => {
//   linesNumber.value = temp
// })
// }
//导出为PDF
const downLoadPDF = (text: string) => {
  center.value.linesNumber = 0 //去除分页
  useSelectMaterial.resetSelectMaterial() // 重置选中模块
  htmlToPdf(text, '#capture')
}

// 保存
const saveHandel = () => {
  console.log('保存了')
}
// 重置
const resetHandler = () => {
  ElMessageBox.confirm('此操作将重置所有设置，是否确定重置？', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: '提示',
    center: true,
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '重置成功',
      })
      //重置数据（使用默认模板）
      resetStoreLocal()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消重置',
      })
    })
}
</script>
<style scoped lang="scss">
@mixin size($w, $h) {
  width: $w;
  height: $h;
}

@keyframes move {
  /*from表示动画的开始位置 也可以使用0%*/
  from {
    width: 300px;
  }

  /*to动画的结束位置 也可以使用100%*/
  to {
    width: 60px;
  }
}

/* 解决自定义滚动条 x 轴显示问题 */
.el-scrollbar__wrap {
  overflow-x: hidden;
}

.big_box {
  background-color: #f3f3f3;
  display: flex;
}

.container_center {
  padding: 0 0 0 0;
  margin: 0 auto;
  margin-top: 60px;
  height: 100vh;
  width: 820px;
  background-color: #fff;

  .scrollbar-demo-item2 {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 120px;
    margin: 1px;
    border-radius: 4px;
    border: 0.6px solid #efefef;
    background: #ffffff;
    color: var(--el-color-primary);
    box-shadow: #c4c4c4;
  }
}

.container_right {
  padding-top: 50px;
  width: 350px;
  height: 100vh;
}

.lines {
  z-index: 10;
  width: 820px;
  height: 24px;
  display: flex;
  align-items: center;
  position: absolute;
  background: #f3f3f3 url(@/assets/images/paging_bg.png) center top no-repeat;
  /* 元素及其子元素文本无法被选中 */
  user-select: none;
  /* //元素不会成为鼠标事件的target */
  pointer-events: none;
  .tips {
    font-size: 9px;
    color: #c7c7c7;
  }

  .page {
    font-size: 9px;
    color: #999999;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
